<?php
class Route
{
	public static $path = '';

	public static $ismatch = false;
	public static $PathMatchName = false;
	public static $PathMatchInfo = array();

	public static $module = 'index';
	public static $controller = 'index';
	public static $action = 'index';

	public static $pathRouter = array();

	public static $args = array();

	public static $error = '';


	public function __construct()
	{}

	//解析请求路径
	public static function parseURI($path)
	{
		self::$path = $path;

		self::$pathRouter = RouteConfig::$Path;

		//检查uri路由
		//如果uri中不含有"/"才会走正则匹配
		if (!empty(self::$pathRouter) && !empty(self::$path) && (strpos(self::$path, '/') === false)) {
			self::preg_parse(self::$pathRouter, self::$path);
		}
		
		$routeInfo = array();
        
        if (!empty(self::$PathMatchName)) { //正则匹配, path匹配到了
            $routeInfo = self::$PathMatchInfo;
        } else {
            $routeInfo = self::analysisPath(self::$path);
        }
        
        self::$module     = $routeInfo['moduleName'];
        self::$controller = $routeInfo['controllerName'];
        self::$action     = $routeInfo['actionName'];
        self::$args       = $routeInfo['args'];
	}

	//正则匹配分析
    //1. 待匹配的字符串跟配置文件中数组的某一个键完全一样
    //2. 没有完全一样的就挨个跟数组的键进行匹配
	public static function preg_parse($router, $subject)
	{
		$match_route = false;
		$path = '';
		$arrMatchArg = [];
		if (!empty($router[$subject])) {
			$match_route = $subject;
			$path = $router[$subject]; //单纯的字符串, 没有正则表达式
		} else {
			foreach ($router as $pattern => $route) {

				preg_match('#'.$pattern.'#', $subject, $matches);
				
				$countMatch = count($matches) - 1; //匹配到的数据个数
				$countDollar = substr_count($route, '$'); //待匹配的字符串中'$'的个数

                //重要
				if ($countMatch == $countDollar) {
					self::$ismatch = true;
					$match_route = $pattern;
					// ["abc_123_456_789" => "$1/$2/$3/id/$4"]
					// 变成 ['$1' => 'abc', '$2' => 123, '$3' => 456, $4 => 789]
					foreach ($matches as $key => $value) {
						$arrMatchArg['$'.$key] = $value;
					}

					// 接上一步: "$1/$2/$3/id/$4"
					// 变成 "abc/123/456/id/789", 方便下一步解析出m c a
					$path = str_replace(array_keys($arrMatchArg), array_values($arrMatchArg), $route);
					break;
				}
			}
		}
        
        self::$PathMatchName = $match_route;
        self::$PathMatchInfo = self::analysisPath($path);
	}

	//分析路径参数
	public static function analysisPath($path)
	{
        $moduleName     = self::$module;
        $controllerName = self::$controller;
        $actionName     = self::$action;
	    $args = array();
	    
		//获得module/controller/action
		$arrPathInfo = explode('/', $path);//存放URL中以正斜线隔开的内容的数组
		!empty($arrPathInfo[0]) && ($moduleName = $arrPathInfo[0]);
		!empty($arrPathInfo[1]) && ($controllerName = $arrPathInfo[1]);
		!empty($arrPathInfo[2]) && ($actionName = $arrPathInfo[2]);

		//存放除module/controller/action之外的参数
		// /a/1/b/2/c/3 ==> ?a=1&b=2&c=3
		// 当键和值不成对出现时,默认最后一个键的值为0
		// 参数中不要出现数字键,否则在合并post,get参数时会出错
		if (count($arrPathInfo) > 3) {
			$arrPath = array_slice($arrPathInfo, 3);
			$intArgNum = count($arrPath);
			if ($intArgNum % 2 != 0) {
				$arrPath[] = 0;//最后补一个0
			}

			for ($i=0; $i<$intArgNum; $i=$i+2) {
				$args[$arrPath[$i]] = $arrPath[$i+1];
			}
		}
		
		return array(
            'moduleName'     => $moduleName,
            'controllerName' => $controllerName,
            'actionName'     => $actionName,
            'args'           => $args
        );
	}

}